% 加载图像并进行预处理
image = imread('pic_measure.png');
gray = rgb2gray(image);

% 转移到 GPU
gray_gpu = gpuArray(gray);

% 去阴影
shadow_rgb = [62, 59, 68]; % Shadow color in RGB
image_rgb = gather(rgb2gray(image)); % Convert back to CPU for comparison
shadow_mask = all(image_rgb == reshape(shadow_rgb, [1, 1, 3]), 3); % Mask where shadow exists
non_shadow_mask = ~shadow_mask; % Mask where non-shadow exists

% Apply to image
image_no_shadow = image;
image_no_shadow(repmat(shadow_mask, [1, 1, 3])) = 255; % Set shadow pixels to white

% 转移到 GPU
enhanced_gpu = gpuArray(image_no_shadow);

% 使用 Sobel 算子进行边缘检测（GPU支持）
edges_gpu = edge(enhanced_gpu, 'Sobel');

% 从 GPU 转回 CPU 保存结果
edges_cpu = gather(edges_gpu);

% 拟合左侧边缘直线
left_edges = edges_cpu(1:find(edges_cpu(:,1), 1, 'first'), :); % First non-zero row from top
[left_edges_y, left_edges_x] = find(left_edges);
p_left = polyfit(left_edges_x, left_edges_y, 1);

% 拟合右侧边缘直线
right_edges = edges_cpu(:, find(edges_cpu(1, :), 1, 'last'):end); % Last non-zero column from right
[right_edges_y, right_edges_x] = find(right_edges);
p_right = polyfit(right_edges_x, right_edges_y, 1);

% 计算两条直线之间的距离
x_intersection = linspace(1, size(edges_cpu, 2), 100);
left_line_y = polyval(p_left, x_intersection);
right_line_y = polyval(p_right, x_intersection);
distance_between_lines = abs(left_line_y - right_line_y);

% 保存拟合结果
output_dir = 'C:\Users\YourName\Documents\MATLAB\results';
if ~exist(output_dir, 'dir')
    mkdir(output_dir);
end

% 画出图像并保存
figure;
imshow(edges_cpu);
hold on;
plot(x_intersection, left_line_y, 'r-', 'LineWidth', 2); % Left edge line
plot(x_intersection, right_line_y, 'b-', 'LineWidth', 2); % Right edge line
title('Fitted Lines on Brake Pad Edge');
saveas(gcf, fullfile(output_dir, 'fitted_lines.png'));

% 计算外围长度
peripheral_length = abs(p_right(2) - p_left(2)); % Difference in y-intercepts gives distance between lines
fprintf('外围长度: %.2f pixels\n', peripheral_length);
